package com.yuandian.bpm.common.websocket.custom;

import com.yuandian.bpm.common.security.service.BpmUser;
import com.yuandian.bpm.common.websocket.holder.SessionKeyGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author bpm
 * @date 2021/10/4 websocket session 标识生成规则
 */
@Configuration
@RequiredArgsConstructor
public class BpmSessionKeyGenerator implements SessionKeyGenerator {

	/**
	 * 获取当前session的唯一标识
	 * @param webSocketSession 当前session
	 * @return session唯一标识
	 */
	@Override
	public Object sessionKey(WebSocketSession webSocketSession) {

		Object obj = webSocketSession.getAttributes().get("USER_KEY_ATTR_NAME");

		if (obj instanceof BpmUser) {
			BpmUser user = (BpmUser) obj;

			if (webSocketSession.getUri() != null && webSocketSession.getUri().toString().contains("nowDate")) {
				/*
				 	请求参数中包含 nowDate 则是通过运维工作台模块发起的请求
						如果仅用 userId 作为唯一区分，会出现消息只发到一台机上的情况(若多台机同时登录同一个账号)
				 */
				Map<String, String> param = parseToMap(webSocketSession.getUri().toString());
				String nowDateStr = param.get("nowDate");
				return user.getId() + nowDateStr;
			}

			// userId 作为唯一区分
			return String.valueOf(user.getId());
		}

		return null;
	}

	/**
	 * 从字符串中解析出键值对
	 * 		“A=a&B=b” -> {"A": "a", "B": "b"}
	 */
	public static Map<String, String> parseToMap(String querystring) {
		Map<String, String> map = new HashMap<>();
		String[] arrSplit = querystring.split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");

			//解析出键值
			if (arrSplitEqual.length > 1) {
				//正确解析
				map.put(arrSplitEqual[0], arrSplitEqual[1]);
			} else {
				if (!Objects.equals(arrSplitEqual[0], "")) {
					//只有参数没有值，不加入
					map.put(arrSplitEqual[0], "");
				}
			}
		}
		return map;
	}

}
